<template>
  <el-form label-position="top" label-width="80px" :model="adGroupForm" :rules="adGroupFormRules"
           ref="adGroupForm">
    <basic-container ref="2-1">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>广告组名称</div>
        </div>
      </div>
      <el-form-item label="" prop="adgroupName" ref="adGroup-adgroupName">
        <el-input v-model="adGroupForm.adgroupName" placeholder="请输入内容" size="mini"
        ></el-input>
      </el-form-item>
    </basic-container>

    <basic-container ref="2-2">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>版位</div>
        </div>
      </div>
      <el-form-item label="">
        <div>
          <el-radio v-model="adGroupForm.placementType" :label="'PLACEMENT_TYPE_AUTOMATIC'"
                    @change="handelChangePlacementType" :disabled="isSuccess">自动版位
          </el-radio>
          <div class="row-tips">
            让新用户安装您的应用
          </div>
        </div>
        <div>
          <el-radio v-model="adGroupForm.placementType" :label="'PLACEMENT_TYPE_NORMAL'"
                    @change="handelChangePlacementType" :disabled="isSuccess">编辑版位
          </el-radio>
        </div>
        <div class="row-tips">
          重新吸引现有用户在您的应用中执行操作。iOS 14.5+ 设备不支持应用再营销。
        </div>
      </el-form-item>
      <el-form-item prop="placement">
        <el-collapse-transition>
          <div v-show="adGroupForm.placementType ==='PLACEMENT_TYPE_NORMAL'">
            <el-checkbox-group v-model="adGroupForm.placement"
                               @change="handleChangePlacement"
                               :disabled="isSuccess">
              <el-checkbox v-for="item in placementsList" :label="item.value" :key="item.value">{{
                  item.label
                }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-collapse-transition>
      </el-form-item>
      <template
        v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
        <el-form-item label="">
          <el-switch
            v-model="adGroupForm.commentDisabled"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            active-text="用户评论"
            inactive-text=""
            :active-value="1"
            :inactive-value="0">
          </el-switch>
          <div class="row-tips">系统自动优化预算分配</div>
        </el-form-item>
        <el-form-item label="">
          <el-switch
            v-model="adGroupForm.videoDownloadDisabled"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            active-text="视频下载"
            inactive-text=""
            :active-value="1"
            :inactive-value="0"
            :disabled="isSuccess"
          >
          </el-switch>
          <div class="row-tips">系统自动优化预算分配</div>
        </el-form-item>
        <el-form-item label="">
          <el-switch
            v-model="adGroupForm.shareDisabled"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            active-text="视频共享"
            inactive-text=""
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </template>
      <template
        v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_PANGLE')">
        <el-form-item label="">
          <el-switch
            v-model="adGroupForm.blockedPangleDisabled"
            :active-color="activeColor"
            :inactive-color="inactiveColor"
            active-text="Pangle 媒体屏蔽列表"
            inactive-text=""
            :active-value="1"
            :inactive-value="0"
            disabled>
          </el-switch>
          <div class="row-tips">Pangle 媒体屏蔽列表</div>
        </el-form-item>
      </template>
    </basic-container>
    <basic-container ref="2-3">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>创意投放方式</div>
        </div>
      </div>
      <el-form-item label="">
        <el-switch
          v-model="adGroupForm.creativeMaterialMode"
          :active-color="activeColor"
          :inactive-color="inactiveColor"
          active-text="程序化创意"
          inactive-text=""
          active-value="DYNAMIC"
          inactive-value="CUSTOM"
          disabled>
        </el-switch>
        <div class="row-tips">创建多个创意素材资产组合，包括视频和广告文案。 广告投放期间将自动向您的受众展示可以达到最理想效果的组合。 查看详情</div>
      </el-form-item>
    </basic-container>
    <basic-container ref="2-4">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>定向</div>
        </div>
      </div>
      <el-form-item label="">
        <div class="promotion-target-card" :class="{'current-promotion':adGroupForm.autoTargetingEnabled===0}"
             @click="adGroupForm.autoTargetingEnabled=0">
          <div class="promotion-target-card-title">
            自定义定向
          </div>
          <div class="promotion-target-card-content">
            手动设置关于要向哪类用户显示广告的条件。
          </div>
        </div>
        <div class="promotion-target-card" :class="{'current-promotion':adGroupForm.autoTargetingEnabled===1}"
             style="cursor: default">
          <div class="promotion-target-card-title">
            自动定向
          </div>
          <div class="promotion-target-card-content">
            手动设置关于要向哪类用户显示广告的条件。
          </div>
        </div>
      </el-form-item>
      <div ref="batchAdGroup">
        <el-form-item label="投放地区" prop="locationIds">
          <el-select v-model="adGroupForm.locationIds" placeholder="请选择" size="mini" multiple filterable
          >
            <el-option
              v-for="item in locationList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语言">
          <el-select v-model="adGroupForm.languages" placeholder="不限" size="mini" multiple filterable
                     clearable
          >
            <el-option v-for="item in languagesList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="adGroupForm.gender" size="mini">
            <el-radio-button v-for="item in genderList" :key="item.value" :label="item.value">{{
                item.label
              }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <cs-radio-checkbox v-model="adGroupForm.age" :props="ageGroupsList"
          ></cs-radio-checkbox>
        </el-form-item>
      </div>
      <el-form-item label="家庭收入"
                    v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
        <el-select v-model="adGroupForm.householdIncome" placeholder="不限" size="mini" multiple clearable>
          <el-option
            v-for="item in householdIncomeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="受众">
        <el-cascader
          size="mini"
          v-model="adGroupForm.audience"
          :options="audiencesList"
          :props="audiencesCascaderProp"
          clearable
          filterable
          ref="adGroupFormAudienceIds"
          @change="handleChangeAdGroupFormAudienceIds"
          :disabled="audiencesBtnLoading"
        ></el-cascader>
        <el-tooltip effect="dark" content="点击刷新，可同步该账户里的可用受众包" placement="top-start">
          <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"
                     @click="getAudiencesList(true)" v-loading="audiencesBtnLoading"></el-button>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="排除受众">
        <el-cascader
          v-model="adGroupForm.excludedAudience"
          size="mini"
          :options="excludedAudiencesList"
          :props="audiencesCascaderProp"
          ref="adGroupFormExcludedAudienceIds"
          clearable
          filterable
          @change="handleChangeAdGroupFormExcludedAudienceIds"
          :disabled="audiencesBtnLoading"
        ></el-cascader>
        <el-tooltip effect="dark" content="点击刷新，可同步该账户里的可用受众包" placement="top-start">
          <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"
                     @click="getAudiencesList(true)" v-loading="audiencesBtnLoading"></el-button>
        </el-tooltip>
      </el-form-item>
      <span style="font-weight: bolder; font-size: 18px;"
            v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">兴趣和行为</span>
      <el-row>
        <el-col :span="12">
          <el-form-item label="预设兴趣"
                        v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
            <el-cascader
              v-model="adGroupForm.interestCategory"
              size="mini"
              :options="tiktokInterestTree"
              :props="{
                      expandTrigger: 'hover',
                      multiple: true,
                      }"
              ref="tiktokInterestTreeC"
              clearable
              filterable
              @change="handleInterestNodeClick"
              :disabled="interestBtnLoading"
            ></el-cascader>
            <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"
                       @click="getTiktokInterestTree(true)" v-loading="interestBtnLoading"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其它兴趣"
                        v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
            <el-select
              v-model="adGroupForm.interestsByKeywordIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              size="mini"
              :remote-method="queryInterestsByKeyword"
              :loading="queryInterestsLoading"
              @change="handleChangeOtherInterest">
              <el-option
                v-for="item in otherInterestList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <template
        v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
        <span style="font-weight: bold;">添加行为:视频互动</span>
        <el-form-item label="定义他们与视频互动行为" prop="videoUserActions.VIDEO_RELATED"
                      ref="adGroup-videoUserActions.VIDEO_RELATED">
          <el-checkbox-group v-model="adGroupForm.videoUserActions.VIDEO_RELATED"
                             @change="handleChangeVideoRelated">
            <el-checkbox label="WATCHED_TO_END">看完</el-checkbox>
            <el-checkbox label="LIKED">点赞</el-checkbox>
            <el-checkbox label="COMMENTED">评论</el-checkbox>
            <el-checkbox label="SHARED">分享</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择他们与哪些类别的视频有互动" prop="videoRelatedCategoryIds"
                      ref="adGroup-videoRelatedCategoryIds">
          <el-cascader
            v-model="adGroupForm.videoRelatedCategory"
            size="mini"
            :options="videoRelatedTree"
            :props="{
                      expandTrigger: 'hover',
                      multiple: true,
                      }"
            ref="videoRelatedTreeC"
            clearable
            filterable
            @change="handleVideoNodeClick"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="选择n天内发生的行为" prop="actionPeriod" ref="adGroup-actionPeriod">
          <el-radio-group v-model="adGroupForm.actionPeriod">
            <el-radio label="7" @click.native.stop.prevent="handleRadioClick('7')">7 天</el-radio>
            <el-radio label="15" @click.native.stop.prevent="handleRadioClick('15')">15 天</el-radio>
          </el-radio-group>
        </el-form-item>
        <span style="font-weight: bold;">添加行为:创作者互动</span>
        <el-form-item label="定义他们与创作者互动的方式" prop="videoUserActions.CREATOR_RELATED"
                      ref="adGroup-videoUserActions.CREATOR_RELATED">
          <el-checkbox-group v-model="adGroupForm.videoUserActions.CREATOR_RELATED">
            <el-checkbox label="FOLLOWING">关注</el-checkbox>
            <el-checkbox label="VIEW_HOMEPAGE">访问主页</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择他们与哪些类别的创作者互动" prop="creatorRelatedCategoryIds"
                      ref="adGroup-creatorRelatedCategoryIds">
          <el-cascader
            v-model="adGroupForm.creatorRelatedCategory"
            size="mini"
            :options="creatorRelatedTree"
            :props="{
                      expandTrigger: 'hover',
                      multiple: true,
                      }"
            ref="creatorRelatedTreeC"
            clearable
            filterable
            @change="handleCreatorNodeClick"
          ></el-cascader>
        </el-form-item>
      </template>
      <span>设备</span>
      <el-form-item label="系统版本">
        <el-select v-model="tempValue" placeholder="不限" disabled size="mini">
          <el-option
            :label="'不限'"
            :value="'不限'">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备机型">
        <el-select v-model="tempValue" placeholder="不限" disabled size="mini">
          <el-option
            :label="'不限'"
            :value="'不限'">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="网络情况">
        <el-checkbox-group v-model="checkboxNetworkState" size="mini" disabled>
          <el-checkbox-button v-for="item in networkStateList" :label="item.label" :key="item.value">
            {{ item.label }}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="运营商">
        <el-select v-model="tempValue" placeholder="不限" disabled size="mini">
          <el-option
            :label="'不限'"
            :value="'不限'">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=""
                    v-if="adGroupForm.placementType ==='PLACEMENT_TYPE_AUTOMATIC'||adGroupForm.placement.includes('PLACEMENT_TIKTOK')">
        <el-switch
          v-model="adGroupForm.expansionEnabled"
          :active-color="activeColor"
          :inactive-color="inactiveColor"
          active-text="定向扩量"
          inactive-text=""
          :active-value="1"
          :inactive-value="0"
          :disabled="adGroupForm.expansionswitch"
        >
        </el-switch>
        <div class="row-tips">启用定向扩量，将会在合适的时机扩大广告的受众范围，从而提升广告转化数。</div>
      </el-form-item>
      <el-collapse-transition>
        <div v-show="adGroupForm.expansionEnabled===1">
          <el-form-item label="只有您选择了至少一个条件的设置才可以使用定向扩展">
            <el-checkbox-group v-model="adGroupForm.expansionTypes">
              <el-checkbox label="CUSTOM_AUDIENCE"
                           :disabled="!(adGroupForm.audienceIds.length>0)||!(adGroupForm.excludedAudienceIds.length>0)">
                受众
              </el-checkbox>
              <el-checkbox label="GENDER" :disabled="adGroupForm.gender ==='GENDER_UNLIMITED'">
                性别
              </el-checkbox>
              <el-checkbox label="AGE" :disabled="adGroupForm.age.length === 0">年龄</el-checkbox>
              <el-checkbox label="INTEREST_AND_BEHAVIOR"
                           :disabled="adGroupForm.interestCategoryIds.length === 0">兴趣和行为
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-collapse-transition>
    </basic-container>
    <basic-container ref="2-5">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>预算&排期</div>
        </div>
      </div>
      <el-form-item label="预算" prop="budget" ref="adGroup-budget">
        <el-input
          :placeholder="adGroupForm.budgetMode === 'BUDGET_MODE_DAY'?'20.00以上': countBudgetForDay()+'.00以上'"
          size="mini"
          v-model="adGroupForm.budget" class="input-with-select"
          oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
          <el-select style="width: 100px" v-model="adGroupForm.budgetMode" slot="prepend" placeholder="请选择"
                     @change="handleAdGroupBudgetChange"
                     :disabled="campaignForm.budgetSwitch&&campaignForm.budgetMode ==='BUDGET_MODE_DAY'">
            <el-option v-for="item in budgetModeList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <template slot="append">USD</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <!--排期-->
        <div slot="label"><span>排期</span><span>时区：UTC{{ formatterTimezone }}</span></div>
        <div>
          <el-radio v-model="adGroupForm.scheduleType" :label="'SCHEDULE_FROM_NOW'"
                    :disabled="adGroupForm.budgetMode === 'BUDGET_MODE_TOTAL'">开始时间
          </el-radio>
          <div class="row-tips">
            从开始时间起持续投放广告
          </div>
        </div>
        <div>
          <el-radio v-model="adGroupForm.scheduleType" :label="'SCHEDULE_START_END'">开始时间&停止时间</el-radio>
        </div>
        <div class="row-tips">
          从开始时间起开始投放广告，到达停止时间自动停止广告投放
        </div>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="scheduleStartTime" ref="adGroup-scheduleStartTime">
            <el-date-picker
              size="mini"
              v-model="adGroupForm.scheduleStartTime"
              :picker-options="pickerOptions"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择开始日期时间"
              :disabled="isSuccess">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="scheduleEndTime" ref="adGroup-scheduleEndTime">
            <el-date-picker
              v-show="adGroupForm.scheduleType==='SCHEDULE_START_END'"
              style="margin-left: 10px"
              size="mini"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="adGroupForm.scheduleEndTime"
              :picker-options="pickerOptions"
              type="datetime"
              placeholder="选择结束日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="分时段">
        <el-radio-group v-model="adGroupForm.dayparting" size="mini">
          <el-radio-button :label="1">全天</el-radio-button>
          <el-radio-button :label="0" disabled>分时段</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-collapse-transition>
          <div v-show="adGroupForm.dayparting === 0">
            <drag-weektime
              v-model="multTimeRange"
              :data="weektimeData"
              v-peach:event="{category: 'components', action: 'dragWeektime'}"
              @on-clear="clearWeektime">
            </drag-weektime>
          </div>
        </el-collapse-transition>
      </el-form-item>
    </basic-container>
    <basic-container ref="2-6">
      <div slot="header" class="card-header">
        <div class="detail-top">
          <div>出价</div>
        </div>
      </div>
      <el-form-item label="优化目标">
        <el-select v-model="adGroupForm.optimizationGoal" placeholder="请选择" size="mini"
                   @change="handleChangeOptimizationGoal" :disabled="isSuccess">
          <el-option
            v-for="item in curOptimizationGoalList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="options.os === 2 && item.value=== 'VALUE'">
          </el-option>
        </el-select>
      </el-form-item>
      <el-collapse-transition>
        <div
          v-show="adGroupForm.optimizationGoal ==='IN_APP_EVENT'||adGroupForm.optimizationGoal ==='INSTALL_IN_APP_EVENT'">
          <el-form-item
            :label="adGroupForm.optimizationGoal ==='IN_APP_EVENT'?'选择要优化投放的应用内事件数据':'选择要优化投放的安装与应用内事件数据'"
            prop="optimizationEvent" ref="adGroup-optimizationEvent">
            <el-select v-model="adGroupForm.optimizationEvent" placeholder="请选择" size="mini"
                       :disabled="optimizationEventLoading || isSuccess">
              <el-option
                v-for="item in optimizationEventList"
                :disabled="item.disabled"
                :key="item.id"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh-right"
                       @click="getOptimizationEventList(true)"
                       v-loading="optimizationEventLoading" :disabled="isSuccess"></el-button>
          </el-form-item>
        </div>
      </el-collapse-transition>
      竞价策略
      <el-form-item label="最高价值" v-if="adGroupForm.optimizationGoal === 'VALUE'" prop="roasBid"
                    ref="adGroup-roasBid">
        <el-checkbox v-model="adGroupForm.isSetROAS" @change="handleRoasCheck"
                     :disabled="isSuccess">设置广告花费回报(ROAS)下限值
        </el-checkbox>
        <el-collapse-transition>
          <div v-show="adGroupForm.isSetROAS">
            <el-input size="mini" v-model="adGroupForm.roasBid"
                      oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"></el-input>
          </div>
        </el-collapse-transition>
      </el-form-item>
      <template v-else>
        <el-form-item>
          <el-radio v-model="adGroupForm.bidType" :label="'BID_TYPE_CUSTOM'" @change="handleChangeBidType"
                    id="dGroup-bidPr" :disabled="isSuccess">
            {{ adGroupForm.optimizationGoal === 'CLICK' ? '出价' : '成本' }}上限
          </el-radio>
          <div class="row-tips">
            平均成本稳定在出价附近或低于您的出价
          </div>
        </el-form-item>
        <el-row v-show="adGroupForm.bidType ==='BID_TYPE_CUSTOM'">
          <el-col :span="10">
            <el-form-item v-show="adGroupForm.optimizationGoal === 'CLICK'" label="每次转化费用" prop="bidPrice"
                          ref="adGroup-bidPrice">
              <el-input size="mini" v-model="adGroupForm.bidPrice"
                        oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                <template slot="append">USD</template>
              </el-input>
            </el-form-item>
            <el-form-item v-show="adGroupForm.optimizationGoal !== 'CLICK'" label="每次转化费用" prop="conversionBidPrice"
                          ref="adGroup-conversionBidPrice">
              <el-input size="mini"
                        v-model="adGroupForm.conversionBidPrice"
                        oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                <template slot="append">USD</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14" v-show="isPangleRO">
            <el-form-item label="次日留存率：">
              <el-input size="mini" v-model="adGroupForm.dailyRetentionRatio">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="adGroupForm.optimizationGoal !== 'INSTALL_IN_APP_EVENT'">
          <el-radio v-model="adGroupForm.bidType" :label="'BID_TYPE_NO_BID'"
                    @change="handleChangeBidType" id="el-bidType-1" :disabled="isSuccess">最低成本
          </el-radio>
        </el-form-item>
      </template>
      <el-link type="primary" @click="AdvancedOpt=!AdvancedOpt">隐藏高级选项</el-link>
      <el-collapse-transition>
        <div v-show="AdvancedOpt">
          <el-form-item label="计费点">
            <div class="row-tips">
              展现（{{ adGroupForm.optimizationGoal === 'CLICK' ? 'CPC' : 'oCPM' }}）
            </div>
          </el-form-item>
          <el-form-item label="投放速度">
            <el-radio v-model="adGroupForm.pacing" :label="'PACING_MODE_SMOOTH'">标准</el-radio>
            <div class="row-tips">
              系统将在所选广告投放时间段根据业务访问量均匀匹配你的预算和广告。 访问量越高，广告投放频次越高，反之亦然。
            </div>
            <el-radio v-show="adGroupForm.bidType === 'BID_TYPE_CUSTOM'" v-model="adGroupForm.pacing"
                      :disabled="adGroupForm.optimizationGoal === 'VALUE'"
                      :label="'PACING_MODE_FAST'">加速
            </el-radio>
          </el-form-item>
        </div>
      </el-collapse-transition>
    </basic-container>
  </el-form>
</template>

<script>
import Moment from "moment";
import DragWeektime from "@/components/DragWeektime/DragWeektime";
import CsRadioCheckbox from "@/components/CsRadioCheckbox/CsRadioCheckbox";
import weektimeData from "@/components/DragWeektime/data/weektime_data";
import {
  getActionCategories,
  getAudiencesInfo,
  getInterestByKeyword,
  getLocationTree, getOptimizationEvent,
  getTiktokInterestTree
} from "@/api/campaign-management/campaign-management";
import {getLanguagesList} from "@/util/beetles";
import _ from "lodash";
import {deepClone} from "@/util/util";

export default {
  name: "AdGroupForm",
  components: {
    DragWeektime,
    CsRadioCheckbox,
  },
  props: {
    options: {
      type: Object
    },
    currentAccountId: {
      type: String
    },
    // timezone: {
    //   type: String
    // },
    isEdit: {
      type: Boolean,
      default: false
    },
    isSuccess: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var validateAdGroupBudget = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入预算'))
      } else if (this.adGroupForm.budgetMode === '') {
        callback(new Error('请选择预算模式'))
      } else {
        if (this.adGroupForm.budgetMode === 'BUDGET_MODE_DAY') {
          if (parseInt(value) < 20) {
            callback(new Error('预算必须大于20'))
          } else {
            callback()
          }
        } else {
          // 计算算天数
          if (parseInt(value) < this.countBudgetForDay()) {
            callback(new Error('预算必须大于' + this.countBudgetForDay()))
          } else {
            callback()
          }
        }

      }
    }
    var validateAdGroupEndTime = (rule, value, callback) => {
      if (this.adGroupForm.scheduleType === 'SCHEDULE_FROM_NOW') {
        callback()
      } else {
        if (value === null) {
          callback(new Error('请选择结束日期'))
        } else if (new Date(this.adGroupForm.scheduleStartTime).getTime() > new Date(value).getTime()) {
          callback(new Error('结束日期必须大于开始时间'))
        } else {
          callback()
        }
      }
    }
    var validateOptimizationEvent = (rule, value, callback) => {
      if (this.adGroupForm.optimizationGoal === 'IN_APP_EVENT' || this.adGroupForm.optimizationGoal === 'INSTALL_IN_APP_EVENT') {
        if (value) {
          callback()
        } else {
          callback(new Error('请选择优化投放数据'))
        }
      } else {
        callback()
      }
    }
    var validateRoasBid = (rule, value, callback) => {
      if (this.adGroupForm.isSetROAS) {
        if (value === '') {
          callback(new Error('请输入ROAS下限值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateBidPrice = (rule, value, callback) => {
      if (this.adGroupForm.bidType === 'BID_TYPE_CUSTOM' && this.adGroupForm.optimizationGoal === 'CLICK') {
        if (value === '') {
          callback(new Error('请输入出价'))
        } else if (parseInt(value) <= 0) {
          callback(new Error('出价必须大于0'))
        } else if (parseInt(value) >= parseInt(this.adGroupForm.budget)) {
          callback(new Error('出价必须小于预算'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateConversionBidPrice = (rule, value, callback) => {
      if (this.adGroupForm.bidType === 'BID_TYPE_CUSTOM' && this.adGroupForm.optimizationGoal !== 'CLICK') {
        if (value === '') {
          callback(new Error('请输入出价'))
        } else if (parseInt(value) <= 0) {
          callback(new Error('出价必须大于0'))
        } else if (parseInt(value) >= parseInt(this.adGroupForm.budget)) {
          callback(new Error('出价必须小于预算'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateVideoRelated = (rule, value, callback) => {
      if (this.adGroupForm.videoRelatedCategoryIds.length > 0) {
        if (value.length === 0) {
          callback(new Error("添加行为:视频互动每一项必须输入"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateVideoRelatedCategoryIds = (rule, value, callback) => {
      if (this.adGroupForm.videoUserActions.VIDEO_RELATED.length > 0) {
        if (value.length === 0) {
          callback(new Error("添加行为:视频互动每一项必须输入"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateActionPeriod = (rule, value, callback) => {
      if (this.adGroupForm.videoUserActions.VIDEO_RELATED.length > 0 || this.adGroupForm.videoRelatedCategoryIds.length > 0) {
        if (value === '') {
          callback(new Error("添加行为:视频互动每一项必须输入"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateCreatorRelated = (rule, value, callback) => {
      if (this.adGroupForm.creatorRelatedCategoryIds.length > 0) {
        if (value.length === 0) {
          callback(new Error("添加行为:创作者互动每一项必须输入"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateCreatorRelatedCategoryIds = (rule, value, callback) => {
      if (this.adGroupForm.videoUserActions.CREATOR_RELATED.length > 0) {
        if (value.length === 0) {
          callback(new Error("添加行为:创作者互动每一项必须输入"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validatePlacement = (rule, value, callback) => {
      if (this.adGroupForm.placementType === 'PLACEMENT_TYPE_NORMAL') {
        if (value.length === 0) {
          callback(new Error("请选择至少一个版位"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      checkboxNetworkState: [], // 废弃
      tempValue: '', // 废弃
      campaignForm: {
        campaignName: '',
        num: 1,
        accountId: ''
      },
      adGroupForm: {
        // 广告组名称
        adgroupName: '',
        // 版位
        placementType: 'PLACEMENT_TYPE_AUTOMATIC',
        // 用户评论开关
        commentDisabled: 1,
        // 视频下载开关（1:开启，0:关闭）
        videoDownloadDisabled: 1,
        shareDisabled: 1,
        // Pangle媒体屏蔽开关（1:开启，0:关闭）
        blockedPangleDisabled: 0,
        // 创意投放方式
        creativeMaterialMode: 'CUSTOM',
        // 自动定向
        autoTargetingEnabled: 0,
        // 预算
        budget: '',
        // 批量类型
        budgetMode: 'BUDGET_MODE_DAY',
        // 对应&组合
        autoCreateType: 1,
        // 排期方式
        scheduleType: 'SCHEDULE_FROM_NOW',
        // 开始时间
        scheduleStartTime: Moment().utc().add(this.options.timezoneOffset, "hours").format("yyyy-MM-DD HH:mm:ss"),
        // 结束时间
        scheduleEndTime: Moment().utc().add(this.options.timezoneOffset, "hours").add(14, "days").format("yyyy-MM-DD HH:mm:ss"),
        // 分时段
        dayparting: 1,
        // 优化目标
        optimizationGoal: 'INSTALL',
        // 优化事件
        optimizationEvent: '',
        // 出价费用
        bidPrice: '',
        conversionBidPrice: '',
        // 次日留存率
        dailyRetentionRatio: '',
        // 选择受众
        audienceIds: [],
        // 排除受众
        excludedAudienceIds: [],
        // 家庭收入
        householdIncome: [],
        // 兴趣
        interestCategoryIds: [],
        // 视频互动
        videoRelatedCategoryIds: [],
        // 作者互动
        creatorRelatedCategoryIds: [],
        // 话题互动 (temp)
        // topicInteraction: '',
        // 设备定向扩量
        expansionEnabled: 0,
        // 国家地区 数组
        locationIds: [],
        // 语言
        languages: [],
        // 性别
        gender: 'GENDER_UNLIMITED',
        // 年龄
        age: [],
        // 竞价策略
        bidType: 'BID_TYPE_NO_BID',
        // 投放速度
        pacing: 'PACING_MODE_SMOOTH',
        // 版位
        placement: [],
        // 设置广告花费回报(ROAS)下限值
        isSetROAS: false,
        //深度事件出价类型
        deepBidType: '',
        // 用于价值优化的ROAS目标值
        roasBid: '',
        // 定向扩量
        expansionTypes: [],
        // 定向扩量阻止开关
        expansionswitch: false,
        // 视频相关行为
        videoUserActions: {
          VIDEO_RELATED: [],
          CREATOR_RELATED: []
        },
        // 选择n天内发生的行为
        actionPeriod: '',
        creatorRelatedCategory: [],
        videoRelatedCategory: [],
        interestCategory: [],
        interestsByKeyword: [],
        interestsByKeywordIds: [],
        excludedAudience: '',
        audience: '',
        platformId: '',
        appId: '',
        // 推广目标
        objectiveType: 'APP_INSTALL',
      },
      activeColor: "#13ce66",
      inactiveColor: "#ccc",
      // adGroup表单校验
      adGroupFormRules: {
        adgroupName: [{required: true, message: '请输入广告组名称', trigger: 'blur'}],
        budget: [{validator: validateAdGroupBudget, trigger: 'blur'}],
        scheduleStartTime: [{required: true, message: '请选择开始时间', trigger: 'change'}],
        scheduleEndTime: [{validator: validateAdGroupEndTime, trigger: 'change'}],
        optimizationEvent: [{validator: validateOptimizationEvent, trigger: 'change'}],
        roasBid: [{validator: validateRoasBid, trigger: 'blur'}],
        bidPrice: [{validator: validateBidPrice, trigger: 'blur'}],
        conversionBidPrice: [{validator: validateConversionBidPrice, trigger: 'blur'}],
        'videoUserActions.VIDEO_RELATED': [{validator: validateVideoRelated, trigger: 'change'}],
        videoRelatedCategoryIds: [{validator: validateVideoRelatedCategoryIds, trigger: 'change'}],
        actionPeriod: [{validator: validateActionPeriod, trigger: 'change'}],
        'videoUserActions.CREATOR_RELATED': [{validator: validateCreatorRelated, trigger: 'change'}],
        creatorRelatedCategoryIds: [{validator: validateCreatorRelatedCategoryIds, trigger: 'change'}],
        placement: [{validator: validatePlacement, trigger: 'change'}],
        locationIds: [{type: 'array', required: true, message: '请选择地区', trigger: 'change'}]
      },
      weektimeData: weektimeData,
      multTimeRange: [],
      // 投放地区
      locationList: [],
      // 语言
      languagesList: [],
      genderList: [{
        label: '不限',
        value: 'GENDER_UNLIMITED'
      }, {
        label: '男性',
        value: 'GENDER_MALE'
      }, {
        label: '女性',
        value: 'GENDER_FEMALE'
      }],
      // 年龄
      ageGroupsList: [
        {
          label: '13-17岁',
          value: 'AGE_13_17'
        }, {
          label: '18-24岁',
          value: 'AGE_18_24'
        }, {
          label: '25-34岁',
          value: 'AGE_25_34'
        }, {
          label: '35-44岁',
          value: 'AGE_35_44'
        }, {
          label: '45-54岁',
          value: 'AGE_45_54'
        }, {
          label: '55+',
          value: 'AGE_55_100'
        },],
      // 家庭收入
      householdIncomeList: [
        {value: "TOP5", label: "家庭收入群体的前5%"},
        {value: "TOP10", label: "家庭收入群体的前10%"},
        {value: "TOP10_25", label: "家庭收入群体的前10-25%"},
        {value: "TOP25_50", label: "家庭收入群体的前25-50%"}
      ],
      optimizationGoalList: [
        {value: "CLICK", label: "点击"},
        {value: "INSTALL", label: "安装"},
        {value: "VALUE", label: "价值"},
        {value: "IN_APP_EVENT", label: "应用内事件"},
        {value: "INSTALL_IN_APP_EVENT", label: "安装与应用内事件数据"}
      ],
      curOptimizationGoalList: [],
      // 版位
      placementsList: [
        // {value: "PLACEMENT_TOPBUZZ", label: "资讯应用系列"},
        {value: "PLACEMENT_TIKTOK", label: "TikTok"},
        {value: "PLACEMENT_PANGLE", label: "Pangle"},
      ],
      // 受众列表
      audiencesList: [],
      excludedAudiencesList: [],
      // 受众选择属性
      audiencesCascaderProp: {
        multiple: true,
        value: 'audienceId',
        label: 'name'
      },
      audiencesBtnLoading: false,
      networkStateList: [
        {
          label: '不限',
          value: '不限'
        }, {
          label: 'WIFI',
          value: 'WIFI'
        }, {
          label: '2G',
          value: '2G'
        }, {
          label: '3G',
          value: '3G'
        }, {
          label: '4G',
          value: '4G'
        }, {
          label: '5G',
          value: '5G'
        },
      ],
      interestBtnLoading: false,
      tiktokInterestTree: [],
      creatorRelatedTree: [],
      queryInterestsLoading: false,
      otherInterestList: [],
      videoRelatedTree: [],
      // 预算模式枚举
      budgetModeList: [{
        label: '日预算',
        value: 'BUDGET_MODE_DAY'
      }, {
        label: '总预算',
        value: 'BUDGET_MODE_TOTAL'
      }],
      optimizationEventLoading: false,
      // 应用内事件
      optimizationEventList: [
        {
          label: "激活",
          value: "ACTIVE",
          disabled: true
        },
        {
          label: "注册",
          value: "ACTIVE_REGISTER",
          disabled: true
        },
        {
          label: "购买",
          value: "ACTIVE_PAY",
          disabled: true
        },
        {
          label: "创建角色",
          value: "CREATE_GAMEROLE",
          disabled: true
        },
        {
          label: "登录",
          value: "LOGIN",
          disabled: true
        },
        {
          label: "完成新手教程",
          value: "COMPLETE_TUTORIAL",
          disabled: true
        },
        {
          label: "次日留存",
          value: "NEXT_DAY_OPEN",
          disabled: true
        },
        {
          label: "App内添加购物车",
          value: "IN_APP_CART",
          disabled: true
        },
        {
          label: "加入心愿单",
          value: "ADD_TO_WISHLIST",
          disabled: true
        },
        {
          label: "打开App",
          value: "LAUNCH_APP",
          disabled: true
        },
        {
          label: "查看内容",
          value: "IN_APP_DETAIL_UV",
          disabled: true
        },
        {
          label: "创建战队",
          value: "CREATE_GROUP",
          disabled: true
        },
        {
          label: "获得销售线索",
          value: "SALES_LEAD",
          disabled: true
        },
        {
          label: "应用内广告点击",
          value: "IN_APP_AD_CLICK",
          disabled: true
        },
        {
          label: "应用内广告展示",
          value: "IN_APP_AD_IMPR",
          disabled: true
        },
        {
          label: "加入战队",
          value: "JOIN_GROUP",
          disabled: true
        },
        {
          label: "达到级别",
          value: "UPDATE_LEVEL",
          disabled: true
        },
        {
          label: "放款",
          value: "LOAN_COMPLETION",
          disabled: true
        },
        {
          label: "评价",
          value: "RATE",
          disabled: true
        },
        {
          label: "搜索",
          value: "SEARCH",
          disabled: true
        },
        {
          label: "花费点数",
          value: "SPEND_CREDITS",
          disabled: true
        },
        {
          label: "解锁关卡",
          value: "UNLOCK_ACHIEVEMENT",
          disabled: true
        },
        //二级事件
        {
          label: "添加付款信息",
          value: "ADD_PAYMENT_INFO",
          disabled: true
        },
        {
          label: "App内下单",
          value: "IN_APP_ORDER",
          disabled: true
        },
        {
          label: "申请贷款",
          value: "LOAN_APPLY",
          disabled: true
        },
        {
          label: "授信",
          value: "LOAN_CREDIT",
          disabled: true
        },
        {
          label: "开始试用",
          value: "START_TRIAL",
          disabled: true
        },
        {
          label: "订阅",
          value: "SUBSCRIBE",
          disabled: true
        },
        {
          label: "购买操作的ROI",
          value: "PURCHASE_ROI",
          disabled: true
        },
      ],
      AdvancedOpt: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      }
    }
  },
  computed: {
    formatterTimezone() {
      if (this.options.timezoneOffset === '') {
        return `+00:00`
      } else {
        if (this.options.timezoneOffset >= 10) {
          return `+${this.options.timezoneOffset}:00`
        } else if (this.options.timezoneOffset >= 0) {
          return `+0${this.options.timezoneOffset}:00`
        } else if (this.options.timezoneOffset > -10) {
          return `-0${Math.abs(this.options.timezoneOffset)}:00`
        } else {
          return `${this.options.timezoneOffset}:00`
        }
      }
    },
    isPangleRO() {
      return this.adGroupForm.placementType === 'PLACEMENT_TYPE_NORMAL'
        && this.adGroupForm.placement.length == 1
        && this.adGroupForm.placement.includes('PLACEMENT_PANGLE')
        && this.adGroupForm.optimizationEvent === 'NEXT_DAY_OPEN'
        && this.adGroupForm.bidType === 'BID_TYPE_CUSTOM'
    },
    checkOptimizationValue() {
      if (this.campaignForm.os === 1) {
        if (this.isHasValue) {
          if (this.adGroupForm.placementType === 'PLACEMENT_TYPE_AUTOMATIC') {
            return false
          } else {
            if (this.adGroupForm.placement.includes("PLACEMENT_TIKTOK")) {
              return false
            } else {
              return true
            }
          }
        } else {
          return true
        }
      } else {
        return true
      }
    },
  },
  created() {
    // this.initOption()
    this.languagesList = getLanguagesList();
    this.curOptimizationGoalList = deepClone(this.optimizationGoalList)
    // this.getAudiencesList()
    // this.getTiktokInterestTree()
    // this.getVideoRelatedTree()
    // this.getCreatorRelatedTree()
    // this.getLocationTree()
    // this.getOptimizationEventList()
  },
  methods: {
    // 清空时间段
    clearWeektime() {
      this.weektimeData.forEach(item => {
        item.child.forEach(t => {
          this.$set(t, 'check', false)
        })
      })
    },
    // 获取地区
    async getLocationTree() {
      const {data: res} = await getLocationTree({
        placements: this.adGroupForm.placementType === 'PLACEMENT_TYPE_AUTOMATIC' ? 'PLACEMENT_TIKTOK,PLACEMENT_PANGLE' : this.adGroupForm.placement.join(',')
      })
      this.locationList = res.data
    },
    // 获取受众列表
    async getAudiencesList(refresh) {
      this.audiencesBtnLoading = true
      const {data: res} = await getAudiencesInfo({
        refresh: refresh || false,
        platformId: this.adGroupForm.platformId,
        // platformId: '7068120188243197954',
      }).finally(() => {
        this.audiencesBtnLoading = false
      })
      this.audiencesRes = res.data
      this.audiencesList = [{name: '自定义受众', audienceId: -1, children: []}, {name: '类似受众', audienceId: -2, children: []}]
      this.audiencesList[0].children = res.data.filter(item => item.type === 0)
      this.audiencesList[1].children = res.data.filter(item => item.type === 1)
      this.excludedAudiencesList = _.cloneDeep(this.audiencesList)
    },
    handleChangeAdGroupFormAudienceIds() {
      this.adGroupForm.audienceIds = this.$refs.adGroupFormAudienceIds.getCheckedNodes(true).map(item => item.value)
      this.setAudienceDisabled(this.excludedAudiencesList, this.adGroupForm.audienceIds)
    },
    handleChangeAdGroupFormExcludedAudienceIds() {
      this.adGroupForm.excludedAudienceIds = this.$refs.adGroupFormExcludedAudienceIds.getCheckedNodes(true).map(item => item.value)
      this.setAudienceDisabled(this.audiencesList, this.adGroupForm.excludedAudienceIds)
    },
    // 受众选择与排除方法
    setAudienceDisabled(Audiencelist, checked) {
      // console.log(Audiencelist, checked)
      Audiencelist.forEach(item => {
        this.$set(item, 'disabled', false)
        item.disabled = false
        if (item.hasOwnProperty('children') && item.children.length > 0) {
          this.setAudienceDisabled(item.children, checked)
        } else {
          if (checked.includes(item.audienceId)) {
            this.$set(item, 'disabled', true)
          } else {
            // item.disabled = false
          }
        }
      })
    },
    // 获取兴趣列表
    async getTiktokInterestTree(refresh) {
      this.interestBtnLoading = true
      const {data: res} = await getTiktokInterestTree({
        refresh: refresh || false
      }).finally(() => {
        this.interestBtnLoading = false
      })
      // console.log(res)
      this.tiktokInterestTree = res.data
      this.tiktokInterestList = []
      this.transformList(res.data, this.tiktokInterestList)
    },
    // 把属性结构结果转换成数组
    transformList(tree, res) {
      tree.forEach(item => {
        if (item.hasOwnProperty('children')) {
          this.transformList(item.children, res)
        } else {
          res.push({
            label: item.label,
            value: item.value
          })
        }
      })
    },
    async queryInterestsByKeyword(queryString) {
      this.queryInterestsLoading = true
      const {data: res} = await getInterestByKeyword(this.currentAccountId, queryString).finally(() => {
        this.queryInterestsLoading = false
      })
      this.otherInterestList = res.data
    },
    // 添加行为:创作者互动
    async getVideoRelatedTree(refresh) {
      const {data: res} = await getActionCategories({
        refresh: refresh || false,
        type: 'VIDEO_RELATED'
      })
      this.videoRelatedTree = res.data
      this.videoRelatedList = []
      this.transformList(res.data, this.videoRelatedList)
    },
    // 添加行为:视频互动
    async getCreatorRelatedTree(refresh) {
      const {data: res} = await getActionCategories({
        refresh: refresh || false,
        type: 'CREATOR_RELATED'
      })
      this.creatorRelatedTree = res.data
      this.creatorRelatedList = []
      this.transformList(res.data, this.creatorRelatedList)
    },
    // 获取应用内事件
    async getOptimizationEventList(refresh) {
      // if (this.optimizationEventLoading) return
      this.optimizationEventLoading = true
      console.log(this.adGroupForm.placement)
      const {data: res} = await getOptimizationEvent({
        appId: this.options.appId,
        objective: this.adGroupForm.objectiveType,
        optimizationGoal: this.adGroupForm.optimizationGoal,
        placement: this.adGroupForm.placement.join(','),
        platformId: this.options.platformId,
        refresh: refresh || false
      }).finally(() => {
        this.optimizationEventLoading = false
      })
      // console.log('事件', res)
      const serverEventList = res.data.map(item => item.value);
      this.optimizationEventList.forEach(item => {
        if (serverEventList.includes(item.value)) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      })
      this.optimizationEventList.sort((a, b) => {
        return a.disabled - b.disabled
      })
      // this.optimizationEventList = res.data
    },
    handelChangePlacementType(val) {
      this.getLocationTree()
      this.clearLocationParams()
      if (val === 'PLACEMENT_TYPE_NORMAL') {
        this.adGroupForm.placement = ["PLACEMENT_TIKTOK", "PLACEMENT_PANGLE"]
      } else {
        this.adGroupForm.placement = []
      }
    },
    // 兴趣选择
    handleInterestNodeClick(data, self, child) {
      this.adGroupForm.interestCategoryIds = this.$refs.tiktokInterestTreeC.getCheckedNodes(true).map(item => item.value)
    },
    handleChangeOtherInterest(val) {
      const prop = this.otherInterestList.filter(item => val.includes(item.id))
      this.adGroupForm.interestsByKeyword.push(...prop)
      this.adGroupForm.interestsByKeyword = _.uniqWith(this.adGroupForm.interestsByKeyword, _.isEqual)
    },
    // 行为视频互动点击
    handleVideoNodeClick() {
      if (this.adGroupForm.videoUserActions.VIDEO_RELATED.length === 0 && this.adGroupForm.videoRelatedCategory.length === 0) {
        this.$refs.adGroupForm.clearValidate('videoRelatedCategoryIds')
        this.$refs.adGroupForm.clearValidate('videoUserActions.VIDEO_RELATED')
      }
      this.adGroupForm.videoRelatedCategoryIds = this.$refs.videoRelatedTreeC.getCheckedNodes(true).map(item => item.value)
    },
    // 行为 作者
    handleCreatorNodeClick() {
      this.adGroupForm.creatorRelatedCategoryIds = this.$refs.creatorRelatedTreeC.getCheckedNodes(true).map(item => item.value)
    },
    handleChangeVideoRelated() {
      if (this.adGroupForm.videoUserActions.VIDEO_RELATED.length === 0 && this.adGroupForm.videoRelatedCategory.length === 0) {
        this.$refs.adGroupForm.clearValidate('videoRelatedCategoryIds')
        this.$refs.adGroupForm.clearValidate('videoUserActions.VIDEO_RELATED')
      }
    },
    // 计算天数预算
    countBudgetForDay() {
      let start = this.adGroupForm.scheduleStartTime.split(' ')[0]
      let end = this.adGroupForm.scheduleEndTime.split(' ')[0]
      if (start < end) {
        let dateSpan
        let iDays
        start = Date.parse(start);
        end = Date.parse(end);
        dateSpan = end - start;
        dateSpan = Math.abs(dateSpan);
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return (iDays + 1) * 20 - 20;
      } else {
        return 20
      }
    },
    // 推广系列预算选择处理
    handleAdGroupBudgetChange(val) {
      this.$refs.adGroupForm.clearValidate('budget')
      if (val === 'BUDGET_MODE_TOTAL') {
        this.adGroupForm.scheduleType = 'SCHEDULE_START_END'
      } else {
        this.adGroupForm.scheduleType = 'SCHEDULE_FROM_NOW'
      }
    },
    // 优化目标选择后事件
    handleChangeOptimizationGoal(val) {
      if(val === 'VALUE') {
        this.$message.info('您选择了创建价值广告，请确保当前账户具备创建价值广告的能力。')
      }
      this.adGroupForm.optimizationEvent = ''
      if (val === 'IN_APP_EVENT' || val === 'INSTALL_IN_APP_EVENT') {
        this.getOptimizationEventList()
      } else {
        //   this.optimizationEventList = []
      }
      if (val === 'INSTALL') {
        this.adGroupForm.bidType = 'BID_TYPE_NO_BID'
      } else {
        this.adGroupForm.bidType = 'BID_TYPE_CUSTOM'
      }
      this.adGroupForm.roasBid = ''
      this.adGroupForm.conversionBidPrice = ''
      this.adGroupForm.bidPrice = ''
    },
    // 勾选roas框触发
    handleRoasCheck(val) {
      if (val) {
        this.adGroupForm.deepBidType = 'VO_MIN_ROAS'
        this.adGroupForm.bidType = 'BID_TYPE_NO_BID'
      } else {
        this.$refs.adGroupForm.clearValidate('roasBid')
        this.adGroupForm.deepBidType = 'VO_HIGHEST_VALUE'
        this.adGroupForm.bidType = 'BID_TYPE_NO_BID'
        this.adGroupForm.roasBid = ''
      }
    },
    // 选择竞价的策略处理
    handleChangeBidType(val) {
      this.$refs.adGroupForm.clearValidate('bidPrice')
      this.adGroupForm.bidPrice = ''
      this.adGroupForm.conversionBidPrice = ''
      this.adGroupForm.pacing = 'PACING_MODE_SMOOTH'
    },
    // 清除已选国家
    clearLocationParams() {
      this.adGroupForm.locationIds = []
    },
    safeSplitCommon(str) {
      if (str === null || str === "" || str === undefined) {
        return []
      }
      return str.split(",")
    },
    initOption(val) {
      if (this.isEdit) {
        let rowCopy = _.cloneDeep(val)
        if (val.videoUserActions === '') {
          rowCopy.videoUserActions = {
            VIDEO_RELATED: [],
            CREATOR_RELATED: []
          }
        } else {
          rowCopy.videoUserActions = JSON.parse(val.videoUserActions)
        }
        rowCopy.objectiveType = 'APP_INSTALL'
        this.adGroupForm = rowCopy
      } else {
        if (val.videoUserActions === '') {
          this.adGroupForm.videoUserActions = {
            VIDEO_RELATED: [],
            CREATOR_RELATED: []
          }
        } else {
          this.adGroupForm.videoUserActions = JSON.parse(val.videoUserActions)
        }
      }
      this.adGroupForm.placement = this.safeSplitCommon(val.placement)
      this.adGroupForm.locationIds = this.safeSplitCommon(val.locationIds)
      this.adGroupForm.languages = this.safeSplitCommon(val.languages)
      this.adGroupForm.age = this.safeSplitCommon(val.age)
      this.adGroupForm.householdIncome = this.safeSplitCommon(val.householdIncome)
      this.adGroupForm.interestCategoryIds = this.safeSplitCommon(val.interestCategoryIds)
      this.adGroupForm.interestsByKeywordIds = this.safeSplitCommon(val.interestsByKeywordIds)
      this.adGroupForm.videoRelatedCategoryIds = this.safeSplitCommon(val.videoRelatedCategoryIds)
      this.adGroupForm.creatorRelatedCategoryIds = this.safeSplitCommon(val.creatorRelatedCategoryIds)
      this.adGroupForm.expansionTypes = this.safeSplitCommon(val.expansionTypes)
      this.adGroupForm.interestCategory = val.interestCategory === '' ? [] : JSON.parse(val.interestCategory)
      this.adGroupForm.interestsByKeyword = val.interestsByKeyword === '' ? [] : JSON.parse(val.interestsByKeyword)
      this.adGroupForm.videoRelatedCategory = val.videoRelatedCategory === '' ? [] : JSON.parse(val.videoRelatedCategory)
      this.adGroupForm.creatorRelatedCategory = val.creatorRelatedCategory === '' ? [] : JSON.parse(val.creatorRelatedCategory)
      this.adGroupForm.adgroupName = val.adgroupName
      this.adGroupForm.placementType = val.placementType
      this.adGroupForm.commentDisabled = val.commentDisabled
      this.adGroupForm.videoDownloadDisabled = val.videoDownloadDisabled
      this.adGroupForm.creativeMaterialMode = val.creativeMaterialMode
      this.adGroupForm.gender = val.gender
      this.adGroupForm.actionPeriod = val.actionPeriod
      this.adGroupForm.expansionEnabled = val.expansionEnabled
      this.adGroupForm.budgetMode = val.budgetMode
      this.adGroupForm.budget = val.budget
      this.adGroupForm.scheduleType = val.scheduleType
      this.adGroupForm.scheduleEndTime = val.scheduleEndTime
      this.adGroupForm.scheduleStartTime = val.scheduleStartTime
      this.adGroupForm.optimizationGoal = val.optimizationGoal
      this.adGroupForm.optimizationEvent = val.optimizationEvent
      this.adGroupForm.bidType = val.bidType
      this.adGroupForm.roasBid = val.roasBid
      this.adGroupForm.bidPrice = val.bidPrice
      this.adGroupForm.conversionBidPrice = val.conversionBidPrice
      this.adGroupForm.dailyRetentionRatio = val.dailyRetentionRatio
      this.adGroupForm.pacing = val.pacing
      this.adGroupForm.platformId = val.platformId
      this.adGroupForm.appId = val.appId
      this.adGroupForm.shareDisabled = val.shareDisabled
      if (val.interestsByKeywordIds.length > 0 && val.interestsByKeyword !== '') {
        this.otherInterestList = JSON.parse(val.interestsByKeyword)
      } else {
        this.otherInterestList = []
      }
      this.getAudiencesList()
      this.getTiktokInterestTree()
      this.getVideoRelatedTree()
      this.getCreatorRelatedTree()
      this.getLocationTree()
      this.getOptimizationEventList()
      this.checkHasValue()
    },
    handleChangePlacement(val) {
      this.getLocationTree()
      this.clearLocationParams()
      if (val.length > 0) {
        this.getOptimizationEventList()
      }
      if (!val.includes('PLACEMENT_TIKTOK')) {
        this.adGroupForm.interestCategory = []
        this.adGroupForm.interestCategoryIds = []
        this.adGroupForm.interestsByKeywordIds = []
        this.adGroupForm.interestsByKeyword = []
        this.adGroupForm.videoUserActions.VIDEO_RELATED = []
        this.adGroupForm.videoRelatedCategory = []
        this.adGroupForm.videoRelatedCategoryIds = []
        this.adGroupForm.actionPeriod = ''
        this.adGroupForm.videoUserActions.CREATOR_RELATED = []
        this.adGroupForm.creatorRelatedCategory = []
        this.adGroupForm.creatorRelatedCategoryIds = []
      }
    },
    handleRadioClick(val) {
      this.adGroupForm.actionPeriod === val ? this.adGroupForm.actionPeriod = '' : this.adGroupForm.actionPeriod = val
    },
    clearForm() {
      this.$refs.adGroupForm.resetFields()
      this.adGroupForm.scheduleStartTime = Moment().utc().add(this.options.timezoneOffset, "hours").format("yyyy-MM-DD HH:mm:ss")
      this.adGroupForm.scheduleEndTime = Moment().utc().add(this.options.timezoneOffset, "hours").add(14, "days").format("yyyy-MM-DD HH:mm:ss")
      this.getAudiencesList()
      this.getTiktokInterestTree()
      this.getVideoRelatedTree()
      this.getCreatorRelatedTree()
      this.getLocationTree()
      this.getOptimizationEventList()
      this.checkHasValue()
    },
    // 校验是否含有价值选项
    async checkHasValue() {
      const {data: res} = await getOptimizationEvent({
        appId: this.options.appId,
        objective: this.adGroupForm.objectiveType,
        optimizationGoal: 'VALUE',
        placement: "PLACEMENT_TIKTOK",
        platformId: this.options.platformId,
        refresh: true
      })
      this.isHasValue = res.data.some(item => item.value.startsWith('PURCHASE'))
    }
  }
}
</script>

<style scoped lang="scss">
.promotion-target-card {
  display: inline-block;
  position: relative;
  width: 260px;
  height: 126px;
  border: 1px solid #eeeeee;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 15px;
  margin-top: 20px;

  .promotion-target-card-title {
    font-size: 16px;
    margin-top: 18px;
    margin-left: 16px;
    line-height: 16px;
    color: #101010;
  }

  .promotion-target-card-content {
    position: absolute;
    font-size: 12px;
    line-height: 12px;
    white-space: nowrap;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #666666;
  }
}

.current-promotion {
  border: 1px solid #34A9FF !important;
}
</style>
